package Task3;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.Callable;

public class ThreadCallable implements Callable {
    public static File f1 = new File("/Users/ZiyangZhang/Desktop/CS/java/Module1Task/src/com/lagou/Module4/src/Task3/CopyDir");
    public static File f2 = new File("/Users/ZiyangZhang/Desktop/CS/java/Module1Task/src/com/lagou/Module4/src/Task3/PasteDir");

    @Override
    public Object call() throws Exception {
        copy(f1,f2);
        System.out.println("文件拷贝完成");
        return null;
    }
    public static void copy(File file1, File file2){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        File[] filesArray = file1.listFiles();
        try {
            for (File tf : filesArray
            ) {
                if (tf.isFile()){
                    fis = new FileInputStream(tf);
                    fos = new FileOutputStream(new File(file2, tf.getName()));
                    byte[] bArr = new byte[1024];
                    int res = 0;
                    while ((res = fis.read(bArr)) != -1) {
                        fos.write(bArr, 0, res);
                    }

                    System.out.println("拷贝文件成功！");
                }
                if (tf.isDirectory()){
                    String str = file2.getAbsolutePath();
                    str = str+"/"+tf.getName();
                    new File(str).mkdir();
                    copy(tf, new File(str));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != fis) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
